package com.lv.common.utils

import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import com.alibaba.android.arouter.utils.TextUtils
import com.alibaba.sdk.android.oss.ClientException
import com.alibaba.sdk.android.oss.ServiceException
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask
import com.alibaba.sdk.android.oss.model.DeleteMultipleObjectRequest
import com.alibaba.sdk.android.oss.model.DeleteMultipleObjectResult
import com.alibaba.sdk.android.oss.model.PutObjectRequest
import com.alibaba.sdk.android.oss.model.PutObjectResult
import com.blankj.utilcode.util.ImageUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.blankj.utilcode.util.ScreenUtils
import com.hw.videoprocessor.VideoProcessor
import com.luck.picture.lib.entity.LocalMedia
import com.lv.common.bean.ALiUpLoadBitmapBean
import com.lv.common.imp.UploadFileListener
import com.lv.common.ktx.getVideoDimensions
import com.lv.common.ktx.readFileToByteArray
import com.lv.common.network.config.SP_KEY_USER_ID
import com.lv.common.utils.YgxUtilsKt.Companion.isInstalled
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.IOException

/**
 * 作者： ygx
 * 创建日期：2023/2/11 2:49 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：
 */
class YgxNetUtilsKt {

    companion object {
        fun sendCode(phone: String): String {
            var sa = ""
            var s: String? = ""
            try {
                val substring = phone.substring(5, 11)
                val split = substring.split("")
                sa = ""
                for (i in split.indices) {
                    if (split[i].isEmpty()) {
                        continue
                    }
                    val integer = Integer.valueOf(split[i])
                    val nu = integer + 1
                    sa += if (nu != 10) {
                        nu
                    } else {
                        0
                    }
                }
                s = MyUtils.DoMd5(sa, 2)
            } catch (e: NumberFormatException) {
                throw RuntimeException(e)
            }
            return s
        }

        fun partToRequestBody(value: String): RequestBody {
            return RequestBody.create("multipart/form-data".toMediaTypeOrNull(), value)
        }

        fun partFilesToRequestBody(mSelectMedia: MutableList<LocalMedia?>): MutableList<MultipartBody.Part> {
            val mPartMedia = mutableListOf<MultipartBody.Part>()

            val files = ArrayList<File>()
//                val size = ArrayList<String>()
            if (mSelectMedia.size > 0) {
                for (i in 0 until mSelectMedia.size) {
                    var upFileName: String? = ""
                    var file: File? = null
                    var compressPath = mSelectMedia[i]?.compressPath
                    if (compressPath.isNullOrEmpty()) {
                        compressPath = mSelectMedia[i]?.realPath
                    }
                    if (compressPath != null && compressPath.isNotEmpty()) {
                        if (compressPath.startsWith("http")) {
                            val filepath = "/sdcard/update/"
//                            if (!TextUtils.isEmpty(compressPath)) { //截取水印图片的真实链接
//                                val split = compressPath.split("\\?".toRegex()).toTypedArray()
//                                compressPath = split[0]
//                            }
                            compressPath = URLEncoder.encodeWithUtf8(compressPath)
                            file = MyUtils.writeTxtToFile(
                                "txt content", filepath, compressPath
                            )
                            files.add(file)
                            upFileName = compressPath
                            // 创建 RequestBody，用于封装构建RequestBody
                            val requestFile =
                                RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    file!!
                                )
                            val multipartBody =
                                MultipartBody.Part.createFormData(
                                    "imageFile",
                                    upFileName,
                                    requestFile
                                )
                            mPartMedia.add(multipartBody)
                        } else {
                            file = File(compressPath)
                            files.add(file)
                            val suffixFromUrl: String = ImageTypeUtil.getSuffixFromUrl(file.name)
                            upFileName = System.currentTimeMillis()
                                .toString() + i + "_WH_" + mSelectMedia[i]?.width + "_" + mSelectMedia[i]?.height + suffixFromUrl
                            if (!(suffixFromUrl.contains("mp4") || suffixFromUrl.contains("avi") || suffixFromUrl.contains(
                                    "wmv"
                                ) || suffixFromUrl.contains("mpeg") || suffixFromUrl.contains("mpg"))
                            ) {
                                val mBitmap = ImageUtils.getBitmap(compressPath)
                                val imageBytes = BitmapUtil.bitmap2Bytes(mBitmap)
//                                val imageBytes = BitmapUtil.bitmap2Bytes(mBitmap, 3 * 1000 * 1000)
                                val width = mBitmap?.width ?: ScreenUtils.getScreenWidth()
                                val height = mBitmap?.height ?: ScreenUtils.getScreenWidth()
                                upFileName = System.currentTimeMillis()
                                    .toString() + i + "_WH_" + width + "_" + height + ".png"

                                // 创建RequestBody
                                val requestBody =
                                    RequestBody.create("image/jpeg".toMediaTypeOrNull(), imageBytes)

                                // 创建MultipartBody
                                val multipartBody =
                                    MultipartBody.Builder().setType(MultipartBody.FORM)

                                        .addFormDataPart("imageFile", upFileName, requestBody)
                                        .build().part(0)
                                mPartMedia.add(multipartBody)
                            } else {
                                // 创建 RequestBody，用于封装构建RequestBody
                                val requestFile =
                                    RequestBody.create(
                                        "multipart/form-data".toMediaTypeOrNull(),
                                        file
                                    )
                                val multipartBody =
                                    MultipartBody.Part.createFormData(
                                        "imageFile",
                                        upFileName,
                                        requestFile
                                    )
                                mPartMedia.add(multipartBody)
                            }

                        }
//                        // 创建 RequestBody，用于封装构建RequestBody
//                        val requestFile =
//                            RequestBody.create("multipart/form-data".toMediaTypeOrNull(), file!!)
//                        val multipartBody =
//                            MultipartBody.Part.createFormData("imageFile", upFileName, requestFile)
//                        mPartMedia.add(multipartBody)
                    }
                }
            } else {
                val multipartBody = MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("", "")
                    .build().part(0)
                mPartMedia.add(multipartBody)
            }
            return mPartMedia
        }

        fun partFilesNoCompressToRequestBody(mSelectMedia: MutableList<LocalMedia?>): MutableList<MultipartBody.Part> {
            val mPartMedia = mutableListOf<MultipartBody.Part>()

            val files = ArrayList<File>()
//                val size = ArrayList<String>()
            if (mSelectMedia.size > 0) {
                for (i in 0 until mSelectMedia.size) {
                    var upFileName: String? = ""
                    var file: File? = null
                    var compressPath = mSelectMedia[i]?.compressPath
                    if (compressPath.isNullOrEmpty()) {
                        compressPath = mSelectMedia[i]?.realPath
                    }
                    if (compressPath != null && compressPath.isNotEmpty()) {
                        if (compressPath.startsWith("http")) {
                            val filepath = "/sdcard/update/"
//                            if (!TextUtils.isEmpty(compressPath)) { //截取水印图片的真实链接
//                                val split = compressPath.split("\\?".toRegex()).toTypedArray()
//                                compressPath = split[0]
//                            }
                            compressPath = URLEncoder.encodeWithUtf8(compressPath)
                            file = MyUtils.writeTxtToFile(
                                "txt content", filepath, compressPath
                            )
                            files.add(file)
                            upFileName = compressPath
                            // 创建 RequestBody，用于封装构建RequestBody
                            val requestFile =
                                RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    file!!
                                )
                            val multipartBody =
                                MultipartBody.Part.createFormData(
                                    "imageFile",
                                    upFileName,
                                    requestFile
                                )
                            mPartMedia.add(multipartBody)
                        } else {
                            file = File(compressPath)
                            files.add(file)
                            val suffixFromUrl: String = ImageTypeUtil.getSuffixFromUrl(file.name)
                            upFileName = System.currentTimeMillis()
                                .toString() + i + "_WH_" + mSelectMedia[i]?.width + "_" + mSelectMedia[i]?.height + suffixFromUrl
                            if (!(suffixFromUrl.contains("mp4") || suffixFromUrl.contains("avi") || suffixFromUrl.contains(
                                    "wmv"
                                ) || suffixFromUrl.contains("mpeg") || suffixFromUrl.contains("mpg"))
                            ) {
                                val mBitmap = ImageUtils.getBitmap(compressPath)
//                                val imageBytes = BitmapUtil.bitmap2Bytes(mBitmap)
//                                val imageBytes = BitmapUtil.bitmap2Bytes(mBitmap, 3 * 1000 * 1000)
                                val width = mBitmap?.width ?: ScreenUtils.getScreenWidth()
                                val height = mBitmap?.height ?: ScreenUtils.getScreenWidth()
                                upFileName = System.currentTimeMillis()
                                    .toString() + i + "_WH_" + width + "_" + height + ".png"

                                // 创建RequestBody
                                val requestBody =
                                    RequestBody.create("image/jpeg".toMediaTypeOrNull(), file)

                                // 创建MultipartBody
                                val multipartBody =
                                    MultipartBody.Builder().setType(MultipartBody.FORM)

                                        .addFormDataPart("imageFile", upFileName, requestBody)
                                        .build().part(0)
                                mPartMedia.add(multipartBody)
                            } else {
                                // 创建 RequestBody，用于封装构建RequestBody
                                val requestFile =
                                    RequestBody.create(
                                        "multipart/form-data".toMediaTypeOrNull(),
                                        file
                                    )
                                val multipartBody =
                                    MultipartBody.Part.createFormData(
                                        "imageFile",
                                        upFileName,
                                        requestFile
                                    )
                                mPartMedia.add(multipartBody)
                            }

                        }
//                        // 创建 RequestBody，用于封装构建RequestBody
//                        val requestFile =
//                            RequestBody.create("multipart/form-data".toMediaTypeOrNull(), file!!)
//                        val multipartBody =
//                            MultipartBody.Part.createFormData("imageFile", upFileName, requestFile)
//                        mPartMedia.add(multipartBody)
                    }
                }
            } else {
                val multipartBody = MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("", "")
                    .build().part(0)
                mPartMedia.add(multipartBody)
            }
            return mPartMedia
        }

        fun partFilesToRequestBody(
            mContext: Context, mSelectMedia: MutableList<LocalMedia?>
        ): MutableList<MultipartBody.Part> {
            val mPartMedia = mutableListOf<MultipartBody.Part>()

            val files = ArrayList<File>()
//                val size = ArrayList<String>()
            if (mSelectMedia.size > 0) {
                for (i in 0 until mSelectMedia.size) {
                    var upFileName: String? = ""
                    var file: File? = null
                    var compressPath = mSelectMedia[i]?.compressPath
                    if (compressPath.isNullOrEmpty()) {
                        compressPath = mSelectMedia[i]?.realPath
                    }
                    if (compressPath != null && compressPath.isNotEmpty()) {
                        if (compressPath.startsWith("http")) {
                            val filepath = "/sdcard/update/"
//                            if (!TextUtils.isEmpty(compressPath)) { //截取水印图片的真实链接
//                                val split = compressPath.split("\\?".toRegex()).toTypedArray()
//                                compressPath = split[0]
//                            }
                            compressPath = URLEncoder.encodeWithUtf8(compressPath)
                            file = MyUtils.writeTxtToFile(
                                "txt content", filepath, compressPath
                            )
                            files.add(file)
                            upFileName = compressPath
                            // 创建 RequestBody，用于封装构建RequestBody
                            val requestFile =
                                RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    file!!
                                )
                            val multipartBody =
                                MultipartBody.Part.createFormData(
                                    "imageFile",
                                    upFileName,
                                    requestFile
                                )
                            mPartMedia.add(multipartBody)
                        } else {
                            file = File(compressPath)
                            files.add(file)
                            val suffixFromUrl: String = ImageTypeUtil.getSuffixFromUrl(file.name)
                            upFileName = System.currentTimeMillis()
                                .toString() + i + "_WH_" + mSelectMedia[i]?.width + "_" + mSelectMedia[i]?.height + suffixFromUrl
                            if (!(suffixFromUrl.contains("mp4") || suffixFromUrl.contains("avi") || suffixFromUrl.contains(
                                    "wmv"
                                ) || suffixFromUrl.contains("mpeg") || suffixFromUrl.contains("mpg"))
                            ) {
//                                val currentTimeMillis = System.currentTimeMillis()
                                val mBitmap = ImageUtils.getBitmap(compressPath)
//                                val currentTimeMillis2 = System.currentTimeMillis()
                                val imageBytes = BitmapUtil.bitmap2Bytes(mBitmap)
//                                val currentTimeMillis3 = System.currentTimeMillis()
//                                LogUtils.e(
//                                    "bitmap==" + (currentTimeMillis2 - currentTimeMillis).toString(),
//                                    "压缩==" + (currentTimeMillis3 - currentTimeMillis2).toString()
//                                )
                                val width = mBitmap?.width ?: 0
                                val height = mBitmap?.height ?: 0
                                upFileName = System.currentTimeMillis()
                                    .toString() + i + "_WH_" + width + "_" + height + ".png"

                                // 创建RequestBody
                                val requestBody =
                                    RequestBody.create("image/jpeg".toMediaTypeOrNull(), imageBytes)

                                // 创建MultipartBody
                                val multipartBody =
                                    MultipartBody.Builder().setType(MultipartBody.FORM)
                                        .addFormDataPart("imageFile", upFileName, requestBody)
                                        .build().part(0)
                                mPartMedia.add(multipartBody)
                            } else {
                                val appDir =
                                    File(MyUtils.getSDPath(mContext), "suyiyong_o_video")
                                if (!appDir.exists()) {
                                    appDir.mkdir()
                                }
                                val with = mSelectMedia[i]?.width ?: ScreenUtils.getScreenWidth()
                                val height = mSelectMedia[i]?.height ?: ScreenUtils.getScreenWidth()
                                upFileName = System.currentTimeMillis()
                                    .toString() + i + "_WH_" + with + "_" + height + suffixFromUrl

                                val fileCompress = File(appDir, upFileName)
                                // 实现视频压缩的逻辑
                                try {
                                    //拿到视频的比特率
                                    val mBitrate = (8500000 * 0.4).toInt()
//                                    val media = MediaMetadataRetriever()
//                                    media.setDataSource(fileCompress.path)
//                                    val extractMetadata =
//                                        media.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE)
//                                    if (extractMetadata != null && extractMetadata.isNotEmpty()) {
//                                        mBitrate = (extractMetadata.toInt() * 0.4).toInt()
//                                    }

//                                    val currentTimeMillis2 = System.currentTimeMillis()
                                    var addMediaCount = 0
                                    VideoProcessor.processor(mContext)
                                        .input(file.path).output(fileCompress.path)
                                        .bitrate(mBitrate).progressListener { progerss ->//8500000
                                            if (progerss.toInt() == 1 && addMediaCount == 0) {
//                                                val currentTimeMillis3 = System.currentTimeMillis()
//                                                LogUtils.e(
//                                                    "视频压缩==" + (currentTimeMillis3 - currentTimeMillis2).toString()
//                                                )
                                                addMediaCount = 1
                                                // 创建 RequestBody，用于封装构建RequestBody
                                                val requestFile =
                                                    RequestBody.create(
                                                        "multipart/form-data".toMediaTypeOrNull(),
                                                        fileCompress
                                                    )
                                                val multipartBody =
                                                    MultipartBody.Part.createFormData(
                                                        "imageFile",
                                                        upFileName,
                                                        requestFile
                                                    )
                                                mPartMedia.add(multipartBody)
                                            }
                                        }.process()
                                } catch (e: Exception) {
                                    // 创建 RequestBody，用于封装构建RequestBody
                                    val requestFile =
                                        RequestBody.create(
                                            "multipart/form-data".toMediaTypeOrNull(),
                                            file
                                        )
                                    val multipartBody =
                                        MultipartBody.Part.createFormData(
                                            "imageFile",
                                            upFileName,
                                            requestFile
                                        )
                                    mPartMedia.add(multipartBody)
                                }
                            }

                        }
                    }
                }
            } else {
                val multipartBody = MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("", "")
                    .build().part(0)
                mPartMedia.add(multipartBody)
            }
            return mPartMedia
        }

        /**
         * 阿里直传
         */
        fun partBitmapToAli(
            mContext: Context,
            mDir: String = "androidWork/",
            mSelectMedia: MutableList<ALiUpLoadBitmapBean?>,
            uploadFileListener: UploadFileListener? = null
        ) {
            if (mSelectMedia.isEmpty()) {
                return
            }
            val upLoadUrls = mutableListOf<String>()

            // 上传文件
            ossBitmapUpload(mContext, mDir, mSelectMedia, upLoadUrls, 0, uploadFileListener)
        }

        /**
         * 	  阿里云OSS上传（默认是异步多文件上传）
         */
        private fun ossBitmapUpload(
            mContext: Context,
            mDir: String,
            mSelectMedia: MutableList<ALiUpLoadBitmapBean?>,
            upLoadUrls: MutableList<String>,
            currentIndex: Int,
            uploadFileListener: UploadFileListener? = null
        ) {
            var myIndex = currentIndex
            if (mSelectMedia.isEmpty()) {
                // 文件全部上传完毕，这里编写上传结束的逻辑，如果要在主线程操作，最好用Handler或runOnUiThead做对应逻辑
                return// 这个return必须有，否则下面报越界异常，原因自己思考下哈
            }
            val compressPath = mSelectMedia[0]?.url ?: ""
            val bitmap = mSelectMedia[0]?.bimap
            if (TextUtils.isEmpty(compressPath) && bitmap == null) {
                mSelectMedia.removeAt(0)
                myIndex++
                // url为空就没必要上传了，这里做的是跳过它继续上传的逻辑。
                ossBitmapUpload(
                    mContext,
                    mDir,
                    mSelectMedia,
                    upLoadUrls,
                    myIndex,
                    uploadFileListener
                )
                return
            }
            if (compressPath.startsWith("http")) {
                mSelectMedia.removeAt(0)
                myIndex++
                // url为空就没必要上传了，这里做的是跳过它继续上传的逻辑。
                upLoadUrls.add(compressPath)
                if (mSelectMedia.isEmpty()) {
                    var mImages = ""
                    for (img in upLoadUrls) {
                        mImages = "$mImages,$img"
                    }
                    if (mImages.startsWith(",")) {
                        mImages = mImages.drop(1)
                    }
                    uploadFileListener?.uploadSuccess(upLoadUrls, mImages)
                } else {
                    ossBitmapUpload(
                        mContext,
                        mDir,
                        mSelectMedia,
                        upLoadUrls,
                        myIndex,
                        uploadFileListener
                    )
                }
            } else {
                var mPutRequest: PutObjectRequest? = null
                var id = SPStaticUtils.getString(SP_KEY_USER_ID, "")
                if (id.length > 4) {
                    id = id.dropLast(4)
                }
                var timeCurrent = System.currentTimeMillis().toString()
                if (timeCurrent.length > 7) {
                    timeCurrent = timeCurrent.drop(7)
                }
                //命名：时间戳后
                val randomString = MyUtils.getRandomString(5)

                var upFileName = ""
                if (bitmap == null) {
                    var videoBytes = compressPath.readFileToByteArray()
                    val (videoW, videoH) = compressPath.getVideoDimensions()
                    var width = videoW
                    var height = videoH
                    if (width <= 0) {
                        width = ScreenUtils.getScreenWidth()
                    }
                    if (height <= 0) {
                        height = ScreenUtils.getScreenWidth()
                    }
                    upFileName =
                        mDir + timeCurrent + myIndex + randomString + id + "_WH_" + width + "_" + height + ".mp4"
                    mPutRequest =
                        PutObjectRequest(AliUpLoadConfig.BUCKET_NAME, upFileName, videoBytes)
                } else {
                    var width = bitmap?.width ?: ScreenUtils.getScreenWidth()
                    var height = bitmap?.height ?: ScreenUtils.getScreenWidth()
                    if (width <= 0) {
                        width = ScreenUtils.getScreenWidth()
                    }
                    if (height <= 0) {
                        height = ScreenUtils.getScreenWidth()
                    }
                    var imageBytes = BitmapUtil.bitmap2Bytes(bitmap)
                    upFileName =
                        mDir + timeCurrent + myIndex + randomString + id + "_WH_" + width + "_" + height + ".jpeg"
                    mPutRequest =
                        PutObjectRequest(AliUpLoadConfig.BUCKET_NAME, upFileName, imageBytes)
                }
                upLoadUrls.add("https://suyiyong.oss-cn-hangzhou.aliyuncs.com/$upFileName")
//            val mBitmap = ImageUtils.getBitmap(compressPath)
//                    val imageBytes = BitmapUtil.bitmap2Bytes(mBitmap, 3 * 1000 * 1000)


                // 下面3个参数依次为bucket名，ObjectKey名，上传文件路径

                // 设置进度回调
//                    mPutRequest.setProgressCallback { request, currentSize, totalSize ->
//                    }

                // 异步上传
                val task: OSSAsyncTask<*>? =
                    AliOssUtils.getInstance()?.getOSS(mContext)?.asyncPutObject(
                        mPutRequest,
                        object : OSSCompletedCallback<PutObjectRequest?, PutObjectResult> {
                            override fun onSuccess(
                                request: PutObjectRequest?,
                                result: PutObjectResult
                            ) {
//                                LogUtils.e("上传成功")
                                // 上传成功
                                mSelectMedia.removeAt(0)
                                myIndex++
                                if (mSelectMedia.isEmpty()) {
                                    var mImages = ""
                                    for (img in upLoadUrls) {
                                        mImages = "$mImages,$img"
                                    }
                                    if (mImages.startsWith(",")) {
                                        mImages = mImages.drop(1)
                                    }
                                    uploadFileListener?.uploadSuccess(upLoadUrls, mImages)
                                } else {
                                    ossBitmapUpload(
                                        mContext, mDir,
                                        mSelectMedia,
                                        upLoadUrls,
                                        myIndex,
                                        uploadFileListener
                                    )// 递归同步效果
                                }

                            }

                            override fun onFailure(
                                request: PutObjectRequest?,
                                clientExcepion: ClientException,
                                serviceException: ServiceException
                            ) {
//                                LogUtils.e("上传失败")
                                // 上传失败
                                // 请求异常。
//                                clientExcepion.printStackTrace()
                                // 服务异常。
//                                LogUtils.e("ErrorCode", serviceException.errorCode)
//                                LogUtils.e("RequestId", serviceException.requestId)
//                                LogUtils.e("HostId", serviceException.hostId)
//                                LogUtils.e("RawMessage", serviceException.rawMessage)

                                uploadFileListener?.uploadFailed("")
                                deleteAliMedia(mContext, upLoadUrls)
                            }
                        })
                // task.cancel(); // 可以取消任务
                // task.waitUntilFinished(); // 可以等待直到任务完成
            }
        }

        /**
         * 阿里直传
         */
        fun partFilesToAli(
            mContext: Context,
            mDir: String = "androidWork/",
            mSelectMedia: MutableList<LocalMedia?>,
            uploadFileListener: UploadFileListener? = null
        ) {
            if (mSelectMedia.isEmpty()) {
                uploadFileListener?.uploadFailed("")
                return
            }
            val upLoadUrls = mutableListOf<String>()

            // 上传文件
            ossUpload(mContext, mDir, mSelectMedia, upLoadUrls, 0, uploadFileListener)
        }

        /**
         * 	  阿里云OSS上传（默认是异步多文件上传）
         */
        private fun ossUpload(
            mContext: Context,
            mDir: String,
            mSelectMedia: MutableList<LocalMedia?>,
            upLoadUrls: MutableList<String>,
            currentIndex: Int,
            uploadFileListener: UploadFileListener? = null
        ) {
            var myIndex = currentIndex
            if (mSelectMedia.isEmpty()) {
                // 文件全部上传完毕，这里编写上传结束的逻辑，如果要在主线程操作，最好用Handler或runOnUiThead做对应逻辑
                return// 这个return必须有，否则下面报越界异常，原因自己思考下哈
            }
            var compressPath = mSelectMedia[0]?.compressPath ?: ""
            if (compressPath.isEmpty()) {
                compressPath = mSelectMedia[0]?.realPath ?: ""
            }
            if (TextUtils.isEmpty(compressPath)) {
                mSelectMedia.removeAt(0)
                myIndex++
                // url为空就没必要上传了，这里做的是跳过它继续上传的逻辑。
                ossUpload(mContext, mDir, mSelectMedia, upLoadUrls, myIndex, uploadFileListener)
                return
            }
            if (compressPath.startsWith("http")) {
                mSelectMedia.removeAt(0)
                myIndex++
                // url为空就没必要上传了，这里做的是跳过它继续上传的逻辑。
                upLoadUrls.add(compressPath)
                if (mSelectMedia.isEmpty()) {
                    var mImages = ""
                    for (img in upLoadUrls) {
                        mImages = "$mImages,$img"
                    }
                    if (mImages.startsWith(",")) {
                        mImages = mImages.drop(1)
                    }
                    uploadFileListener?.uploadSuccess(upLoadUrls, mImages)
                } else {
                    ossUpload(mContext, mDir, mSelectMedia, upLoadUrls, myIndex, uploadFileListener)
                }
            } else {
                val file = File(compressPath)
                if (!file.exists()) {
                    mSelectMedia.removeAt(0)
                    myIndex++
                    // 文件为空或不存在就没必要上传了，这里做的是跳过它继续上传的逻辑。
                    ossUpload(mContext, mDir, mSelectMedia, upLoadUrls, myIndex, uploadFileListener)
                    return
                }
                var mPutRequest: PutObjectRequest? = null
                var id = SPStaticUtils.getString(SP_KEY_USER_ID, "")
                if (id.length > 4) {
                    id = id.dropLast(4)
                }
                var timeCurrent = System.currentTimeMillis().toString()
                if (timeCurrent.length > 7) {
                    timeCurrent = timeCurrent.drop(7)
                }
                // 文件后缀
                val suffixFromUrl: String = ImageTypeUtil.getSuffixFromUrl(file.name)
                if (!(suffixFromUrl.contains("mp4") || suffixFromUrl.contains("avi") || suffixFromUrl.contains(
                        "wmv"
                    ) || suffixFromUrl.contains("mpeg") || suffixFromUrl.contains("mpg"))
                ) {
                    //命名：时间戳后
                    val randomString = MyUtils.getRandomString(5)
                    val mBitmap = ImageUtils.getBitmap(compressPath)
//                    val imageBytes = BitmapUtil.bitmap2Bytes(mBitmap, 3 * 1000 * 1000)
                    val imageBytes = BitmapUtil.bitmap2Bytes(mBitmap)
                    val width = mBitmap?.width ?: ScreenUtils.getScreenWidth()
                    val height = mBitmap?.height ?: ScreenUtils.getScreenWidth()
                    val upFileName =
                        mDir + timeCurrent + myIndex + randomString + id + "_WH_" + width + "_" + height + suffixFromUrl
                    upLoadUrls.add("https://suyiyong.oss-cn-hangzhou.aliyuncs.com/$upFileName")
                    // 下面3个参数依次为bucket名，ObjectKey名，上传文件路径
                    mPutRequest =
                        PutObjectRequest(AliUpLoadConfig.BUCKET_NAME, upFileName, imageBytes)
                    // 设置进度回调
//                    mPutRequest.setProgressCallback { request, currentSize, totalSize ->
//                    }
                } else {
                    val randomString = MyUtils.getRandomString(5)
                    val upFileName =
                        mDir + timeCurrent + myIndex + randomString + id + "_WH_" + mSelectMedia[0]?.width + "_" + mSelectMedia[0]?.height + suffixFromUrl
                    upLoadUrls.add("${Constants.ALIHEADER}$upFileName")
                    // 下面3个参数依次为bucket名，ObjectKey名，上传文件路径
                    mPutRequest =
                        PutObjectRequest(AliUpLoadConfig.BUCKET_NAME, upFileName, compressPath)
                    // 设置进度回调
//                    mPutRequest.setProgressCallback { request, currentSize, totalSize ->
//                    }
                }

                // 异步上传
                val task: OSSAsyncTask<*>? =
                    AliOssUtils.getInstance()?.getOSS(mContext)?.asyncPutObject(
                        mPutRequest,
                        object : OSSCompletedCallback<PutObjectRequest?, PutObjectResult> {
                            override fun onSuccess(
                                request: PutObjectRequest?,
                                result: PutObjectResult
                            ) {
                                LogUtils.e("上传成功")
                                // 上传成功
                                mSelectMedia.removeAt(0)
                                myIndex++
                                if (mSelectMedia.isEmpty()) {
                                    var mImages = ""
                                    for (img in upLoadUrls) {
                                        mImages = "$mImages,$img"
                                    }
                                    if (mImages.startsWith(",")) {
                                        mImages = mImages.drop(1)
                                    }
//                                    showToast("图片上传阿里成功")
                                    uploadFileListener?.uploadSuccess(upLoadUrls, mImages)
                                } else {
                                    ossUpload(
                                        mContext, mDir,
                                        mSelectMedia,
                                        upLoadUrls,
                                        myIndex,
                                        uploadFileListener
                                    )// 递归同步效果
                                }

                            }

                            override fun onFailure(
                                request: PutObjectRequest?,
                                clientExcepion: ClientException,
                                serviceException: ServiceException
                            ) {
                                LogUtils.e("上传失败")
                                // 上传失败
                                // 请求异常。
//                                clientExcepion.printStackTrace()
                                // 服务异常。
//                                LogUtils.e("ErrorCode", serviceException.errorCode)
//                                LogUtils.e("RequestId", serviceException.requestId)
//                                LogUtils.e("HostId", serviceException.hostId)
//                                LogUtils.e("RawMessage", serviceException.rawMessage)

                                uploadFileListener?.uploadFailed("")
                                deleteAliMedia(mContext, upLoadUrls)
                            }
                        })
                // task.cancel(); // 可以取消任务
                // task.waitUntilFinished(); // 可以等待直到任务完成
            }
        }

        /**
         * 上传失败时删除已上传文件
         */
        fun deleteAliMedia(mContext: Context, upLoadUrls: MutableList<String>) {
            // 设置需要删除的多个Object完整路径。Object完整路径中不能包含Bucket名称。
            val objectKeys: MutableList<String> = ArrayList()
            var net = ""
            upLoadUrls.forEach { item ->
                net = item
                if (item.startsWith(Constants.ALIHEADER)) {
                    net = item.substring(Constants.ALIHEADER.length, item.length)
                }
                objectKeys.add(net)
            }

            // 设置为简单模式，只返回删除失败的文件列表。
            val request = DeleteMultipleObjectRequest(AliUpLoadConfig.BUCKET_NAME, objectKeys, true)

            AliOssUtils.getInstance()?.getOSS(mContext)?.asyncDeleteMultipleObject(
                request,
                object :
                    OSSCompletedCallback<DeleteMultipleObjectRequest?, DeleteMultipleObjectResult?> {
                    override fun onSuccess(
                        request: DeleteMultipleObjectRequest?,
                        result: DeleteMultipleObjectResult?
                    ) {
//                        Log.i("DeleteMultipleObject", "success")
                    }

                    override fun onFailure(
                        request: DeleteMultipleObjectRequest?,
                        clientException: ClientException,
                        serviceException: ServiceException
                    ) {
                        // 请求异常。
                        if (clientException != null) {
                            // 客户端异常，例如网络异常等。
                            clientException.printStackTrace()
                        }
                        if (serviceException != null) {
                            // 服务端异常。
//                            LogUtils.e("ErrorCode", serviceException.errorCode)
//                            LogUtils.e("RequestId", serviceException.requestId)
//                            LogUtils.e("HostId", serviceException.hostId)
//                            LogUtils.e("RawMessage", serviceException.rawMessage)
                        }
                    }
                })
        }


        fun readFileToByteArray(filePath: String): ByteArray? {
            val file = File(filePath)
            if (!file.exists()) {
                LogUtils.e("FileUtils", "文件不存在: $filePath")
                return null
            }

            return try {
                FileInputStream(file).use { fis ->
                    ByteArrayOutputStream().use { bos ->
                        val buffer = ByteArray(1024)
                        var bytesRead: Int
                        while (fis.read(buffer).also { bytesRead = it } != -1) {
                            bos.write(buffer, 0, bytesRead)
                        }
                        bos.toByteArray()
                    }
                }
            } catch (e: IOException) {
                LogUtils.e("FileUtils", "读取文件失败: ${e.message}")
                null
            }
        }

        /**
         * 判断手机是否安装了QQ。
         */
        fun isQQInstalled() = isInstalled("com.tencent.mobileqq")

        /**
         * 判断手机是否安装了微信。
         */
        fun isWechatInstalled() = isInstalled("com.tencent.mm")

        /**
         * AUTHOR:AbnerMing
         * INTRODUCE:判断微信是否安装
         */
        fun isAliInstalled(activity: Activity): Boolean {
            val uri: Uri = Uri.parse("alipays://platformapi/startApp")
            val intent = Intent(Intent.ACTION_VIEW, uri)
            val componentName: ComponentName? = intent.resolveActivity(activity.packageManager)
            return componentName != null
        }

    }
}